package com.xxx.server.config.security.component;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class JwtAuthencationTokenFilter extends OncePerRequestFilter {


    //获取jwt令牌头部信息
    @Value("${jwt.tokenHeader}")
    private String tokenHeader;
    @Value("${jwt.tokenHead}")
    private String tokenHead;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private UserDetailsService userDetailsService;


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {

        //获取要验证的tokenHeader信息，假设 现在的token令牌是已经登录的
        String authheader = request.getHeader(tokenHeader);
        //  如果 令牌信息不为空，并且是以设置的头部信息开头的
        if (null != authheader && authheader.startsWith(tokenHead)){
            //取字节依据tokenHead的长度
            String authToken = authheader.substring(tokenHead.length());
            //  根据 token 获取用户名
            String username = jwtTokenUtil.getUsernameFromToken(authToken);
            //token 存在但是未登录，就是security里面没有认证内容
            if (null != username && null == SecurityContextHolder.getContext().getAuthentication()){
                //  通过用户名登录
                UserDetails userDetails = userDetailsService.loadUserByUsername(username);
                //验证token是否有效
                if (jwtTokenUtil.validateToken(authToken,userDetails)){
                    UsernamePasswordAuthenticationToken authenticationToken = new
                            UsernamePasswordAuthenticationToken(userDetails,null,userDetails.getAuthorities());
                    authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                    SecurityContextHolder.getContext().setAuthentication(authenticationToken);
                }
            }

        }
        //放行
        filterChain.doFilter(request,response);
    }
}
